from flask import jsonify, request, render_template, flash
from flask_login import current_user

from app.libs.helper import is_isbn_or_key
from app.modes.gift import Gift
from app.modes.wish import Wish
from app.spider.yushu_book import YuShuBook
from app.view_modes.trade import TradeInfo
from . import web
from app.forms.book import SearchFrom
from app.view_modes.book import BookViewModel, BookCollection
import json


@web.route('/book/search')
def search():
    """
    :param q: 普通关键字 isbn
    :param page:
    """

    # 验证层
    form = SearchFrom(request.args)
    books = BookCollection()  # 最终要返回的数据

    if form.validate():  # validate() 获取参数校验的结果
        q = form.q.data.strip()
        page = form.page.data
        isbn_or_key = is_isbn_or_key(q)
        yushu_book = YuShuBook()

        if isbn_or_key == 'isbn':
            yushu_book.search_by_isbn(q)
        else:
            yushu_book.search_by_keyword(q, page)

        books.fill(yushu_book, q)
        # return jsonify(books.__dict__)
        # lambda __dict__ 知识点 default定义一个方法使用
        # （__dict__）解析其他的对象，使dumps()方法的参数为字典类型
        # return json.dumps(books,default=lambda o :o.__dict__)
    else:
        flash('搜索关键字不符合要求，请重新输入')
        # return jsonify(form.errors)
    return render_template('search_result.html', books=books)


# 书籍页面详情
@web.route('/book/<isbn>/detail')
def book_detail(isbn):
    # 默认情况下这个图书对一个用户来说不在礼物清单也不在心愿清单
    has_in_gifts = False
    has_in_wishes = False
    # 获取书籍数据
    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    book = BookViewModel(yushu_book.first)

    if current_user.is_authenticated:  # 判断用户是否登录
        if Gift.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():  # 查询用户的礼物数据
            has_in_gifts = True
        if Wish.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():  # 查询用户的心愿数据
            has_in_wishes = True
    # 取所有赠送者的信息和索要者的信息
    trade_gifts = Gift.query.filter_by(isbn=isbn, launched=False).all()
    trade_wishes = Wish.query.filter_by(isbn=isbn, launched=False).all()

    trade_gifts_model = TradeInfo(trade_gifts)
    trade_wishes_model = TradeInfo(trade_wishes)

    return render_template('book_detail.html', book=book, wishes=trade_wishes_model, gifts=trade_gifts_model
                           , has_in_gifts=has_in_gifts, has_in_wishes=has_in_wishes)


@web.route('/test')
def test():
    r = {
        'name': '',
        'age': 19,
        'sex': '男'
    }
    # 消息闪现
    # html上展示['hello qiyue', 'hello jiuyue']
    flash('hello qiyue')
    flash('hello jiuyue')
    # 模板 html
    return render_template('test.html', data=r)
